
// import * as d3 from "../lib/d3.js";
import * as d3 from "d3";
import {ariaControls} from "./util.js";
import {uniq} from "../util/arrays.js";

/**
 * @param {Element[]} nodes
 * @returns d3 selection of unique elements referenced by the specified nodes' <i>aria-controls</i> attribute
 */
export function ariaControlsOf(nodes) {
    const controls = uniq(nodes.map(ariaControls));
    if (controls.length > 1) {
        throw new Error();  // all nodes must control the same set of elements
    }
    return d3.selectAll(controls[0]);
}

/**
 * @param elements a d3 selection of elements.
 * @returns a d3 selection of all unique parent elements.
 */
export function parentsOf(elements) {
    const parents = elements.select(function() { return this.parentElement; }).nodes();
    return d3.selectAll(uniq(parents));
}

/**
 * @param elements a d3 selection of elements.
 * @returns a d3 selection of all child elements.
 */
export function childrenOf(elements) {
    return elements.selectAll(function() { return this.children; });
}

/**
 * @param elements a d3 selection of elements.
 * @returns a d3 selection of all siblings (not including the provided elements).
 */
export function siblingsOf(elements) {
    const self = new Set(elements.nodes());
    return childrenOf(parentsOf(elements)).filter(function() { return !self.has(this); });
}
